package cn.edu.hhu.servlet.admin;

import cn.edu.hhu.Bean.Admin;
import cn.edu.hhu.Bean.Student;
import cn.edu.hhu.service.AdminService;
import cn.edu.hhu.service.Impl.AdminServiceImpl;
import cn.edu.hhu.service.Impl.StudentServiceImpl;
import cn.edu.hhu.service.StudentService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;


@WebServlet("/admin/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1获取数据
        String input_verifycode = request.getParameter("verifycode");
        Map<String, String[]> map = request.getParameterMap();
        //2封装对象
        Admin admin = new Admin();
        try {
            BeanUtils.populate(admin, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //用户名和密码不能为空
        if (admin.getAid() == null || admin.getAid().length() == 0 || admin.getPwd() == null || admin.getPwd().length() == 0) {
            //提示信息
            request.setAttribute("login_msg", "学号或密码不能为空！");
            //跳转登陆页面
            request.getRequestDispatcher("/admin/login.jsp").forward(request, response);
            return;
        }
        //4验证码校验
        String true_verifycode = (String) request.getSession().getAttribute("verifycode");
        if (!true_verifycode.equalsIgnoreCase(input_verifycode)) {
            //提示信息
            request.setAttribute("login_msg", "验证码错误！");
            //跳转登陆页面
            request.getRequestDispatcher("/admin/login.jsp").forward(request, response);
            return;
        }
        //5调用service
        AdminService adminService = new AdminServiceImpl();
        Admin loginAdmin = adminService.login(admin);
        System.out.println(loginAdmin);
        //6判断是否登录成功
        if (loginAdmin != null) {
            //登陆成功
            //存入session
            request.getSession().setAttribute("loginAdmin", loginAdmin);
            //跳转页面
            response.sendRedirect(request.getContextPath() + "/admin/home.jsp");
        } else {
            //登陆失败
            //提示信息
            request.setAttribute("login_msg", "用户名或密码错误！");
            //跳转页面
            request.getRequestDispatcher("/admin/login.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

}
